package com.freewater.javabase.demo.nio;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

public class FileChannelDemo {
    public static void main(String[] args) throws IOException {
        clearData();
        writeData();
        readData();
        readDataFromPosition();
    }

    private static void readData() throws IOException {
        RandomAccessFile file = new RandomAccessFile("data/nio-data.txt", "rw");
        final FileChannel channel = file.getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(5);
        int read = channel.read(buffer);
        while (read != -1) {
            System.out.println("read " + read + " bytes");
            buffer.flip();
            while (buffer.hasRemaining()) {
                System.out.println((char) buffer.get());
            }
            buffer.clear();
            read = channel.read(buffer);
        }
        channel.close();
    }

    private static void readDataFromPosition() throws IOException {
        RandomAccessFile file = new RandomAccessFile("data/nio-data.txt", "rw");
        final FileChannel channel = file.getChannel();
        final long position = channel.position();
        System.out.println("nowPosition: " + position);
        channel.position(channel.size() - 1);
        System.out.println("newPosition:" + channel.position());

        // 修改position后，最后只读取到文件的最后一个字符
        ByteBuffer buffer = ByteBuffer.allocate(5);
        int read = channel.read(buffer);
        while (read != -1) {
            System.out.println("read " + read + " bytes");
            buffer.flip();
            while (buffer.hasRemaining()) {
                System.out.println((char) buffer.get());
            }
            buffer.clear();
            read = channel.read(buffer);
        }
        channel.close();
    }

    private static void writeData() throws IOException {
        RandomAccessFile file = new RandomAccessFile("data/nio-data.txt", "rw");
        final FileChannel channel = file.getChannel();

        String newData = "hello world";
        ByteBuffer buffer = ByteBuffer.allocate(48);
        buffer.clear();
        buffer.put(newData.getBytes(StandardCharsets.UTF_8));
        buffer.flip();

        while (buffer.hasRemaining()) {
            channel.write(buffer);
        }
        channel.close();
    }

    private static void clearData() throws IOException {
        RandomAccessFile file = new RandomAccessFile("data/nio-data.txt", "rw");
        final FileChannel channel = file.getChannel();
        channel.truncate(0);
        channel.close();
    }
}
